/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/sort-comp */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Row, Col, Tree, Button, Divider, Spin, message, Modal, Affix } from 'antd';
import InfoCheck from '@/components/InfoCheck';
import { debounce, isObject } from 'lodash';
import styles from './index.less';

const { DirectoryTree, TreeNode } = Tree;
const { confirm } = Modal;
const noop = () => {};
@connect(({ loading, user, station, operator }) => ({
  station,
  user,
  company_site_id: operator.company_site_id,
  hasSearchOperator: operator.hasSearch,
  deleting: loading.effects['station/deleteStation'],
  getting: loading.effects['station/getStationList'],
}))
export default class StationTree extends Component {
  state = {};

  componentDidUpdate(prevProps) {
    const {
      company_site_id,
      station: { company_info },
      hasSearchOperator,
    } = this.props;
    const { company_site_id: old_company_site_id } = prevProps;
    // 搜索过业务员才执行
    if (company_site_id != old_company_site_id && hasSearchOperator) {
      this.onSelect(
        company_site_id == 0 // 当站点id为0时，说明是总的站点，否则代表是子站点
          ? [`${company_info.brand_code}`]
          : [`${company_site_id || old_company_site_id}`],
        hasSearchOperator,
      );
    }
  }

  onSelect = debounce(
    (keys, hasSearchOperator) => {
      const { onSelect = noop } = this.props;
      if (isObject(hasSearchOperator)) {
        hasSearchOperator = false;
      }
      this.setCurrentStation(keys, hasSearchOperator)(onSelect);
    },
    300,
    {
      leading: true,
      trailing: false,
    },
  );

  getCurrentStation = keys => {
    const {
      station: { list, company_info },
    } = this.props;
    const newList = [...list];
    if (company_info) {
      newList.unshift(company_info);
    }
    const currentStation = newList.filter(item => (item.brand_code || item.site_id) == keys[0]);
    return currentStation[0] || null;
  };

  updateState = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'station/updateState',
      payload,
    });
  };

  showConfirm = params => {
    confirm({
      okText: '确定',
      cancelText: '取消',
      title: '温馨提示',
      ...params,
    });
  };

  setCurrentStation = (keys, hasSearchOperator) => {
    const currentStation = this.getCurrentStation(keys);
    this.updateState({
      currentStation,
      selectedKeys: keys,
    });
    return fn => {
      fn(currentStation, hasSearchOperator);
    };
  };

  onAdd = () => {
    const { onAdd = noop } = this.props;
    onAdd();
  };

  onDelete = () => {
    const {
      onDelete = noop,
      dispatch,
      station: { currentStation, selectedKeys },
    } = this.props;
    if (!currentStation) {
      message.error('请先选择要删除的站点');
      return;
    }
    const { site_id } = currentStation;
    this.showConfirm({
      content: '是否确定删除该站点！',
      onOk: () => {
        dispatch({
          type: 'station/deleteStation',
          payload: {
            site_id,
          },
        }).then(() => {
          this.onSelect(selectedKeys);
          onDelete(currentStation);
        });
      },
    });
  };

  handleInfoReady(data) {
    if (!data.name) return;
    const { dispatch } = this.props;
    dispatch({
      type: 'station/getStationList',
    }).then(res => {
      const { selectedKeys } = res;
      if (selectedKeys) {
        this.onSelect(selectedKeys);
      }
    });
  }

  render() {
    const {
      station: { list, selectedKeys, company_info },
      getting = false,
      deleting = false,
      children,
      footerTools = false,
    } = this.props;
    let trees = null;
    const hasMainSite = !!company_info;
    if (hasMainSite) {
      trees = list
        ? [{ list, name: company_info.brand_name, brand_code: company_info.brand_code || '' }]
        : null;
    } else {
      trees = list;
    }

    return (
      <InfoCheck onReady={this.handleInfoReady.bind(this)}>
        <Row type="flex" className={styles['station-wrap']}>
          <Col md={4} sm={24} xs={24}>
            <Affix offsetTop={65}>
              <Spin spinning={getting || deleting}>
                {trees && (
                  <DirectoryTree
                    selectedKeys={selectedKeys}
                    defaultExpandAll
                    onSelect={this.onSelect}
                    expandAction="doubleClick"
                  >
                    {trees.map((parent = {}) => (
                      <TreeNode
                        title={parent.name || parent.site_name}
                        key={parent.brand_code || parent.site_id}
                        className={styles.colerWeight}
                        isLeaf={!hasMainSite} // 当没有主站点时
                      >
                        {parent.list &&
                          parent.list.map(child => (
                            <TreeNode
                              title={child.site_name}
                              key={child.site_id}
                              isLeaf
                              className={styles.coler}
                            />
                          ))}
                      </TreeNode>
                    ))}
                  </DirectoryTree>
                )}
                {footerTools && (
                  <Row className={styles['station-button']}>
                    <Button onClick={this.onAdd}>添加站点</Button>
                    <Divider type="vertical" />
                    <Button onClick={this.onDelete}>删除站点</Button>
                  </Row>
                )}
              </Spin>
            </Affix>
          </Col>
          <Col md={20} sm={24} xs={24}>
            <div className="col-scroll-view">{children}</div>
          </Col>
        </Row>
      </InfoCheck>
    );
  }
}
